/**
 * meilele.com Inc.
 * Copyright (c) 2004-2016 All Rights Reserved.
 */
package com.gpagers.ui;

import java.util.Date;

import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.TableEditor;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableItem;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gpagers.core.MyJob;
import com.gpagers.core.ObjectRef;
import com.gpagers.core.ScheduleInstance;
import com.gpagers.core.UuidUtils;
import com.gpagers.file.FileSDK;

/**
 * 
 * @author liuzijie@meilele.com
 * @version $Id: Task.java, v 0.1 2016年5月9日 上午11:34:17 liuzijie@meilele.com Exp $
 */
public class Task extends Thread {

    Logger logger = LoggerFactory.getLogger(Task.class);

    private Table   table  = null;
    private boolean stop   = false;
    private Button  expression;
    private Label   labelt = null;
    private String  expressionTextGB;

    public Task(Table table) {
        this.table = table;
    }

    /**
     * 弹出探究任务ui框
     */
    public void popAddTaskUI(int index, String name, String expression) {
        EditNewTaskUi shell = new EditNewTaskUi(ObjectRef.mainShell, this, index, name, expression);
        ObjectRef.currentEditorTask = shell;
        Rectangle rect = ObjectRef.mainShell.getBounds();
        Rectangle bouns = shell.getBounds();
        int x = rect.x + (rect.width - bouns.width) / 2;
        int y = rect.y + (rect.height - bouns.height) / 2;
        shell.setLocation(x, y);
        shell.layout();
        shell.open();
    }

    @SuppressWarnings("deprecation")
    public void createTableItem(final String name, String expressiontext, String triggerState) {
        final TableItem item = new TableItem(table, SWT.CENTER);
        item.setText(name);
        item.setImage(new Image(ObjectRef.display, ObjectRef.imagePath + "images/task.png"));

        expressionTextGB = expressiontext;
        TableEditor editor = new TableEditor(table);
        editor.grabHorizontal = true;
        editor.grabVertical = true;
        labelt = new Label(table, SWT.CENTER);
        labelt.setImage(ObjectRef.greenImage);
        labelt.setBackground(ObjectRef.display.getSystemColor(SWT.TRANSPARENCY_ALPHA));
        editor.setEditor(labelt, item, 1);
        ObjectRef.tableStates.add(labelt);
        labelt.addMouseListener(new MouseListener() {
            @Override
            public void mouseUp(MouseEvent arg0) {
            }

            @Override
            public void mouseDown(MouseEvent arg0) {
                stop = (stop ? false : true);
                table.setSelection(item);
                int row = table.getSelectionIndex();
                if (stop) {
                    try {
                        ScheduleInstance.getInstance().pauseTrigger(ObjectRef.triggerList.get(row),
                            ObjectRef.TRIGGER_GROUP);
                    } catch (SchedulerException e1) {
                        logger.error("", e1);
                    }
                } else {
                    try {
                        ScheduleInstance.getInstance().resumeTrigger(ObjectRef.triggerList.get(row),
                            ObjectRef.TRIGGER_GROUP);
                    } catch (SchedulerException e1) {
                        logger.error("", e1);
                    }
                }
                //PAUSED,NORMAL
                String state = ScheduleInstance.getInstance()
                    .getTriggerState(ObjectRef.triggerList.get(row), ObjectRef.TRIGGER_GROUP);
                ObjectRef.persisData.set(row, name + "|" + expressionTextGB + "|" + state);
                FileSDK.writeLog(ObjectRef.persisData);
            }

            @Override
            public void mouseDoubleClick(MouseEvent arg0) {
            }
        });

        expression = new Button(table, SWT.CENTER);
        expression.setEnabled(false);
        expression.setFont(new Font(ObjectRef.display, "宋体", 13, SWT.SHADOW_NONE));
        expression.setText(expressiontext);
        editor = new TableEditor(table);
        editor.grabHorizontal = true;
        editor.grabVertical = true;
        editor.setEditor(expression, item, 2);

        editor = new TableEditor(table);
        editor.grabHorizontal = true;
        editor.grabVertical = true;
        final Button editorbtn = new Button(table, SWT.CENTER);
        editorbtn.setImage(new Image(ObjectRef.display, ObjectRef.imagePath + "images/edit1.png"));
        editorbtn.setText("编辑");
        editor.setEditor(editorbtn, item, 3);
        editorbtn.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                table.setSelection(item);
                int row = table.getSelectionIndex();
                popAddTaskUI(row, item.getText(), expression.getText());
            }
        });

        editor = new TableEditor(table);
        editor.grabHorizontal = true;
        editor.grabVertical = true;
        final Button deletebtn = new Button(table, SWT.CENTER);
        deletebtn.setImage(new Image(ObjectRef.display, ObjectRef.imagePath + "images/delete.png"));
        deletebtn.setText("删除");
        editor.setEditor(deletebtn, item, 4);
        deletebtn.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                table.setSelection(item);
                int row = table.getSelectionIndex();
                try {
                    ScheduleInstance.getInstance().deleteTrigger(ObjectRef.triggerList.get(row),
                        ObjectRef.TRIGGER_GROUP);
                } catch (SchedulerException e1) {
                    logger.error("", e1);
                }
                ObjectRef.tableStates.remove(labelt);
                ObjectRef.triggerList.remove(row);
                ObjectRef.jobList.remove(row);
                ObjectRef.persisData.remove(row);
                FileSDK.writeLog(ObjectRef.persisData);
                labelt.dispose();
                expression.dispose();
                editorbtn.dispose();
                deletebtn.dispose();
                table.remove(row);
                table.layout();

                Event ex = new Event();
                ex.widget = table;
                ex.type = SWT.KeyDown;
                ObjectRef.display.post(ex);
            }
        });

        //schedule job
        try {
            String jobName = UuidUtils.getUUID();
            JobDetail jobDetail = ScheduleInstance.getInstance().defineJob(MyJob.class, jobName,
                ObjectRef.JOB_GROUP);
            jobDetail.getJobDataMap().put("msg", name);
            Date startTime = new Date();
            Date endTime = new Date();
            endTime.setYear(3000);
            String triggerName = UuidUtils.getUUID();
            ObjectRef.triggerList.add(table.getItemCount() - 1, triggerName);
            ObjectRef.jobList.add(table.getItemCount() - 1, jobName);
            Trigger trigger = ScheduleInstance.getInstance().defineCronTrigger(triggerName,
                ObjectRef.TRIGGER_GROUP, expression.getText(), startTime, endTime, 2);
            ScheduleInstance.getInstance().schedulJob(jobDetail, trigger);
            if (!ObjectRef.NORMAL.equals(triggerState)) {
                ScheduleInstance.getInstance().pauseTrigger(triggerName, ObjectRef.TRIGGER_GROUP);
                stop = true;
            }
            //PAUSED,NORMAL
            String state = ScheduleInstance.getInstance().getTriggerState(triggerName,
                ObjectRef.TRIGGER_GROUP);
            ObjectRef.persisData.add(name + "|" + expressiontext + "|" + state);
            FileSDK.writeLog(ObjectRef.persisData);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        this.start();
    }

    public void editTableItem(int index, String name, String expressiontext) {
        TableItem item = table.getItem(index);
        item.setText(name);
        expression.setText(expressiontext);
        try {
            Scheduler scheduler = ScheduleInstance.getInstance().getScheduler();
            JobDetail jobDetail = ScheduleInstance.getInstance().defineJob(MyJob.class,
                ObjectRef.jobList.get(index), ObjectRef.JOB_GROUP);
            jobDetail.getJobDataMap().put("msg", name);
            ScheduleInstance.getInstance().updateJob(jobDetail, scheduler);
            ScheduleInstance.getInstance().updateTriggerExp(ObjectRef.triggerList.get(index),
                ObjectRef.TRIGGER_GROUP, expressiontext, scheduler);
            try {
                stop = true;
                ScheduleInstance.getInstance().pauseTrigger(ObjectRef.triggerList.get(index),
                    ObjectRef.TRIGGER_GROUP);
                //PAUSED,NORMAL
                String state = ScheduleInstance.getInstance()
                    .getTriggerState(ObjectRef.triggerList.get(index), ObjectRef.TRIGGER_GROUP);
                expressionTextGB = expressiontext;
                ObjectRef.persisData.set(index, name + "|" + expressiontext + "|" + state);
                FileSDK.writeLog(ObjectRef.persisData);
            } catch (SchedulerException e1) {
                logger.error("", e1);
            }
        } catch (SchedulerException e) {
            logger.error("", e);
        }
    }

    public Table getTable() {
        return table;
    }

    public void setTable(Table table) {
        this.table = table;
    }

    public void run() {
        while (true) {
            if (labelt == null) {
                continue;
            } else if (!labelt.isDisposed()) {
                ObjectRef.display.asyncExec(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            if (!labelt.getImage().equals(ObjectRef.blackImage))
                                labelt.setImage(ObjectRef.blackImage);
                            else {
                                if (stop) {
                                    labelt.setImage(ObjectRef.redImage);
                                } else {
                                    labelt.setImage(ObjectRef.greenImage);
                                }

                            }
                        } catch (Exception e) {
                            return;
                        }
                    }
                });
            } else {
                break;
            }
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                logger.error("", e);
            }
        }
    }
}
